package cn.biplam.back.bean.ddl.sql2db;

import java.util.Iterator;
import java.util.Map.Entry;

import cn.biplam.back.sql.ddl.Index;
import cn.biplam.back.sql.ddl.Table;
import cn.biplam.common.client.DbResource;
import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.common.wrapper.KvMap;

public class IndexParser {

	/**数据源信息*/
	private DbResource mDbResource;
	/**Table对象*/
	private Table mTable;
	/**存储表的多个列结构(每个列结构包含一组字段)*/
	private KvMap<String, Index> Indexs=null;

	public IndexParser(DbResource mDbResource,Table mTable){
		this.mDbResource = mDbResource;
		this.mTable = mTable;
		this.Indexs = this.mTable.Indexs;
	}

	/**
	 * 功能   得到索引创建语句
	 * @return
	 */
	public String getCreateIndex()throws ErrorMessage {

		String sIndex = "";

		try {
			if("1".equals(this.mDbResource.getDbtype())){
				sIndex = this.getCreateIndexOracle();
			}
		} catch (Exception e) {
			ErrorMessage mErrorMessage = new ErrorMessage(e);
			throw mErrorMessage;
		}

		return sIndex;
	}

	/**
	 * 功能   得到索引创建语句
	 * @return
	 */
	public String getDropIndex()throws ErrorMessage {

		String sIndex = "";

		try {
			if("1".equals(this.mDbResource.getDbtype())){
				sIndex = this.getDropIndexOracle();
			}
		} catch (Exception e) {
			ErrorMessage mErrorMessage = new ErrorMessage(e);
			throw mErrorMessage;
		}

		return sIndex;
	}

	/**
	 * 功能   得到索引创建语句
	 * @return
	 */
	private String getCreateIndexOracle(){
		/**列字段迭代器*/
		Iterator<Entry<String, Index>> ite ;

		/**初始化*/
		ite= this.Indexs.getIterator();
		StringBuilder sb = new StringBuilder();

		@SuppressWarnings("unused")
		Index mIndex = null;
		while(ite.hasNext()){
			mIndex = ite.next().getValue();
//			sb.append("create index "+mIndex.getIndexName()+" on "+this.mTable.getPhysicalName()+" ("+mIndex.getIndexColumnName()+");\n");
		}

		return sb.toString();
	}

	/**
	 * 功能   得到索引创建语句
	 * @return
	 */
	private String getDropIndexOracle(){
		/**列字段迭代器*/
		Iterator<Entry<String, Index>> ite ;

		/**初始化*/
		ite= this.Indexs.getIterator();
		StringBuilder sb = new StringBuilder();

		Index mIndex = null;
		while(ite.hasNext()){
			mIndex = ite.next().getValue();
			sb.append("drop index "+mIndex.getIndexName()+";\n");
		}

		return sb.toString();
	}
}
